package com.frank.service.impl;

import com.frank.dao.UserMapper;
import com.frank.dto.JsonResult;
import com.frank.dto.LoginDto;
import com.frank.feign.ResumeFeign;
import com.frank.model.Resume;
import com.frank.model.User;
import com.frank.model.UserCriteria;
import com.frank.service.UserService;
import com.frank.service.TokenService;
import io.jsonwebtoken.JwtException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private TokenService tokenService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ResumeFeign resumeFeign;

    @Override
    public LoginDto loginService(String phoneNum, String password) {

        UserCriteria userCriteria = new UserCriteria();
        userCriteria.createCriteria().andPhoneEqualTo(phoneNum).andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(userCriteria);
        if (users.isEmpty()){
            return null;
        }
        return new LoginDto(tokenService.createToken(phoneNum,password), phoneNum, users.get(0).getUserName(), users.get(0).getId());
    }

    @Override
    public boolean registerService(String phoneNum, String password) {
        User user = new User();
        user.setPhone(phoneNum);
        user.setPassword(password);

        if (userMapper.insertSelective(user) == 1){

            Resume resume = new Resume();
            resume.setUserId(user.getId());

            JsonResult jsonResult = resumeFeign.addResume(resume);

            return jsonResult.getStatus() == 200;

        }else {
            return false;
        }
    }

    @Override
    public boolean checkToken(String token) {
        UserCriteria userCriteria = new UserCriteria();

        try {
            String phone = tokenService.parseToken(token);
            userCriteria.createCriteria().andPhoneEqualTo(phone);
        }catch (JwtException e){
            return false;
        }

        List<User> userList = userMapper.selectByExample(userCriteria);

        return !userList.isEmpty();
    }
}
